<template>
  <div class="app-container">
    <el-steps :active="active" align-center finish-status="success" process-status="finish">
      <el-step title="商家信息" />
      <el-step title="结算方式和账户" />
      <el-step title="支付方式" />
      <el-step title="场景图片" />
    </el-steps>
    <el-form v-if="formData !== {}" ref="FormRef" :model="formData" :rules="formRules" class="form-wrap" label-position="right" label-width="180px" size="default">
      <!-- 商家信息 -->
      <div v-if="active === 0">
        <el-alert
          :closable="false"
          class="mb20"
          show-icon
          title="温馨提示：带*号为必填；入网类型保存后不能再修改。上传身份证自动识别 身份证信息,上传营业执照自动识别 执照信息,识别信息需重新确认"
          type="warning"
        />

        <el-row>
          <el-col :span="12">
            <el-form-item label="入网类型" prop="netType">
              <el-select v-model="formData.netType" :clearable="true" :filterable="true" placeholder="请选入网类型">
                <el-option v-for="dict in laiqianle_register_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否直接接入" prop="isDirectConnect">
              <el-checkbox v-model="formData.isDirectConnect" :clearable="true" label="直接接入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否电子签约" prop="isUseElecAgreement">
              <el-radio-group v-model="formData.isUseElecAgreement" class="ml-4">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formData.isDirectConnect">
          <el-col :span="12">
            <el-form-item label="所属银联机构号" prop="unionPayInsNo">
              <el-input v-model="formData.unionPayInsNo" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银联商户号" prop="unionPayMrchntNo">
              <el-input v-model="formData.unionPayMrchntNo" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="商户名称" prop="merchantName">
              <el-input v-model="formData.merchantName" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商户简称" prop="shortName">
              <el-input v-model="formData.shortName" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="formData.netType !== '3'">
          <el-col :span="12">
            <el-form-item label="执照类型" prop="licenceType">
              <el-select v-model="formData.licenceType" :clearable="true" :filterable="true">
                <el-option v-for="(item, index) in laiqianle_license_type" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执照编号" prop="licenceNo">
              <el-input v-model="formData.licenceNo" :clearable="true" placeholder="请输入统一社会信用代码" type="text" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col v-if="formData.netType !== '3'" :span="12">
            <el-row>
              <el-col :span="20">
                <el-form-item label="执照有限期" prop="licenceExpireDate">
                  <el-date-picker v-model="formData.licenceExpireDate" :clearable="true" format="YYYY-MM-DD" is-range type="date" value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-checkbox v-model="checkboxValue1" label="长期" @change="(value) => (formData.licenceExpireDate = value ? '2199-12-31' : null)" />
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省市区" required>
              <el-col :span="8">
                <el-form-item prop="addressinfoId.province">
                  <el-select v-model="formData.addressinfoId.province" :clearable="true" :filterable="true" placeholder="请选择省" @change="handleProvinceChange">
                    <el-option v-for="item in provinceOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="addressinfoId.city">
                  <el-select v-model="formData.addressinfoId.city" :clearable="true" :filterable="true" placeholder="请选择市" @change="handleCityChange">
                    <el-option v-for="item in cityOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="addressinfoId.district">
                  <el-select v-model="formData.addressinfoId.district" :clearable="true" :filterable="true" placeholder="请选择区">
                    <el-option v-for="item in areaOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="经营类型" prop="manageTypeId">
              <el-cascader
                v-model="formData.manageTypeId"
                filterable
                :options="businessTypeOptions"
                :props="{ value: 'code', label: 'name', emitPath: false }"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商户地址" prop="addressinfoId.address">
              <el-input v-model="formData.addressinfoId.address" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="经营范围" prop="manageScope">
              <el-input v-model="formData.manageScope" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="法人名称" prop="lepCertName">
              <el-input v-model="formData.lepCertName" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件类型" prop="lepCertType">
              <el-select v-model="formData.lepCertType" :clearable="true" :filterable="true">
                <el-option v-for="item in laiqianle_card_type" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="法人证件编号" prop="lepCertNo">
              <el-input v-model="formData.lepCertNo" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-col :span="20">
                <el-form-item label="法人证件有效日期" prop="lepCertExpireDate">
                  <el-date-picker v-model="formData.lepCertExpireDate" clearable format="YYYY-MM-DD" is-range type="date" value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-checkbox v-model="checkboxValue2" label="长期" @change="(value) => (formData.lepCertExpireDate = value ? '2199-12-31' : null)" />
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="formData.contactName" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人手机号" prop="contactMobile">
              <el-input v-model="formData.contactMobile" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="注册资金" prop="registeredCapital">
              <el-input v-model="formData.registeredCapital" :clearable="true" type="number">
                <template #append>万元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="formData.remarks" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item :rules="[{ required: true, message: '请上传证件正面', trigger: 'change' }]" label="证件正面" prop="fileList[0].path">
              <ImageUpload1 v-model="formData.fileList[0].path" @upload-event="(value) => handleImageEvent(value, 'card')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :rules="[{ required: true, message: '请上传证件反面', trigger: 'change' }]" label="证件反面" prop="fileList[1].path">
              <ImageUpload1 v-model="formData.fileList[1].path" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          v-if="formData.netType !== '3'"
          :rules="[{ required: true, message: '请上传营业执照', trigger: 'change' }]"
          label="营业执照"
          prop="fileList[2].path"
        >
          <ImageUpload1 v-model="formData.fileList[2].path" @upload-event="(value) => handleImageEvent(value, 'back')" />
        </el-form-item>
      </div>

      <!-- 结算方式和账户 -->
      <div v-if="active === 1">
        <el-alert :closable="false" class="mb20" show-icon title="温馨提示：此账号为结算账号(入账账号),上传银行卡自动识别 银行卡信息,识别信息需重新确认" type="warning" />
        <el-row>
          <el-col :span="12">
            <el-form-item label="账号性质" prop="settleAccount.bankAccountType">
              <el-radio-group v-model="formData.settleAccount.bankAccountType">
                <el-radio :disabled="formData.netType === '3'" :label="1">对公</el-radio>
                <el-radio :label="2">对私</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" />
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="settleAccount.bankAccountNo">
              <el-input v-model="formData.settleAccount.bankAccountNo" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号名称" prop="settleAccount.bankAccountName">
              <el-input v-model="formData.settleAccount.bankAccountName" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="银行类型" prop="settleAccount.bankCode">
              <!--@change="(value) => handleBankChange(value, 'settleAccount')"-->
              <el-select v-model="formData.settleAccount.bankCode" :clearable="true" :filterable="true">
                <el-option v-for="item in bankOptions" :key="item.id" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开户行省市">
              <el-col :span="12">
                <el-form-item>
                  <el-select v-model="province" :clearable="true" :filterable="true" placeholder="请选择省" @change="handleProvinceChange1">
                    <el-option v-for="item in provinceOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-select v-model="city" :clearable="true" :filterable="true" placeholder="请选择市">
                    <el-option v-for="item in cityOptions1" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户行" prop="settleAccount.openBank">
              <el-select
                v-model="formData.settleAccount.openBank"
                :clearable="true"
                :filterable="true"
                :loading="openBankLoading"
                :remote="true"
                :remote-method="openBankRemoteMethod"
                :remote-show-suffix="true"
                :reserve-keyword="true"
              >
                <el-option v-for="item in settleAccountOpenBankOptions" :key="item.id" :label="item.bankName" :value="item.bankName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formData.settleAccount.bankAccountType === 2">
          <el-col :span="12">
            <el-form-item label="证件类型" prop="settleAccount.accountIdentityType">
              <el-select v-model="formData.settleAccount.accountIdentityType" :clearable="true" :filterable="true">
                <el-option v-for="item in laiqianle_card_type" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号" prop="settleAccount.accountIdentityNo">
              <el-input v-model="formData.settleAccount.accountIdentityNo" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-if="formData.settleAccount.bankAccountType === 2" :span="12">
            <el-form-item label="预留手机" prop="settleAccount.acctMobile">
              <el-input v-model="formData.settleAccount.acctMobile" :clearable="true" type="text" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :rules="[{ required: true, message: '请上传结算账户正面', trigger: 'change' }]" label="结算账户正面" prop="fileList[3].path">
              <ImageUpload1 v-model="formData.fileList[3].path" @upload-event="(value) => handleImageEvent(value, 'bank')" />
            </el-form-item>
          </el-col>
          <template v-if="formData.netType === '2' && formData.settleAccount.bankAccountType === 2 && formData.settleAccount.bankAccountName !== formData.lepCertName">
            <el-col :span="12">
              <el-form-item :rules="[{ required: true, message: '请上传委托入款授权照片' }]" label="委托入款授权照片" prop="fileList[9].path">
                <ImageUpload1 v-model="formData.fileList[9].path" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :rules="[{ required: true, message: '请上传法人和入账人手持身份证的合照' }]" label="法人和入账人手持身份证的合照" prop="fileList[10].path">
                <ImageUpload1 v-model="formData.fileList[10].path" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :rules="[{ required: true, message: '请上传非法人身份证正面' }]" label="非法人身份证正面" prop="fileList[11].path">
                <ImageUpload1 v-model="formData.fileList[11].path" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :rules="[{ required: true, message: '请上传非法人身份证反面' }]" label="非法人身份证反面" prop="fileList[12].path">
                <ImageUpload1 v-model="formData.fileList[12].path" />
              </el-form-item>
            </el-col>
          </template>
          <template v-if="formData.netType === '1' && formData.settleAccount.bankAccountType === 2 && formData.settleAccount.bankAccountName !== formData.lepCertName">
            <el-col :span="12">
              <el-form-item :rules="[{ required: true, message: '请上传委托入款授权照片' }]" label="委托入款授权照片" prop="fileList[9].path">
                <ImageUpload1 v-model="formData.fileList[9].path" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :rules="[{ required: true, message: '请上传非法人身份证正面' }]" label="非法人身份证正面" prop="fileList[11].path">
                <ImageUpload1 v-model="formData.fileList[11].path" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :rules="[{ required: true, message: '请上传非法人身份证反面' }]" label="非法人身份证反面" prop="fileList[12].path">
                <ImageUpload1 v-model="formData.fileList[12].path" />
              </el-form-item>
            </el-col>
          </template>
        </el-row>

        <el-alert
          v-if="
            (formData.netType === '1' && formData.settleAccount.bankAccountType === 2) ||
            (formData.netType === '2' && formData.settleAccount.bankAccountType === 2 && formData.settleAccount.bankAccountName !== formData.lepCertName)
          "
          :closable="false"
          class="mb20"
          show-icon
          title="温馨提示：此账号为备案账号"
          type="info"
        />
        <div
          v-if="
            (formData.netType === '1' && formData.settleAccount.bankAccountType === 2) ||
            (formData.netType === '2' && formData.settleAccount.bankAccountType === 2 && formData.settleAccount.bankAccountName !== formData.lepCertName)
          "
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="账号性质" prop="filingAccount.bankAccountType">
                <el-radio-group v-model="formData.filingAccount.bankAccountType">
                  <el-radio :label="1">对公</el-radio>
                  <el-radio :disabled="formData.netType === '1'" :label="2">对私</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" />
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="银行账号" prop="filingAccount.bankAccountNo">
                <el-input v-model="formData.filingAccount.bankAccountNo" :clearable="true" type="text" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账号名称" prop="filingAccount.bankAccountName">
                <el-input v-model="formData.filingAccount.bankAccountName" :clearable="true" type="text" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="银行类型" prop="filingAccount.bankCode">
                <!--@change="(value) => handleBankChange(value, 'settleAccount')"-->
                <el-select v-model="formData.filingAccount.bankCode" :clearable="true" :filterable="true">
                  <el-option v-for="item in bankOptions" :key="item.id" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="开户行省市">
                <el-col :span="12">
                  <el-form-item>
                    <el-select v-model="province" :clearable="true" :filterable="true" placeholder="请选择省" @change="handleProvinceChange1">
                      <el-option v-for="item in provinceOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item>
                    <el-select v-model="city" :clearable="true" :filterable="true" placeholder="请选择市">
                      <el-option v-for="item in cityOptions1" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户行" prop="filingAccount.openBank">
                <el-select
                  v-model="formData.filingAccount.openBank"
                  :clearable="true"
                  :filterable="true"
                  :loading="openBankLoading"
                  :remote="true"
                  :remote-method="openBankRemoteMethod"
                  :remote-show-suffix="true"
                  :reserve-keyword="true"
                >
                  <el-option v-for="item in filingAccountOpenBankOptions" :key="item.id" :label="item.bankName" :value="item.bankName" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item :rules="[{ required: true, message: '请上传备案账户正面' }]" label="备案账户正面" prop="fileList[4].path">
                <ImageUpload1 v-model="formData.fileList[4].path" @upload-event="(value) => handleImageEvent(value, 'bank1')" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商户变更申请表" prop="fileList[13].path">
              <ImageUpload1 v-model="formData.fileList[13].path" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 支付方式 -->
      <div v-if="active === 2">
        <el-row>
          <el-col :span="12">
            <el-form-item label="借记卡费率" prop="cardPay.debitRate">
              <el-input-number v-model="formData.cardPay.debitRate" :clearable="true" :precision="2" :step="0.01" placeholder="不用加 % 例如 0.05" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="贷记卡费率" prop="cardPay.feeRate">
              <el-input-number v-model="formData.cardPay.feeRate" :clearable="true" :precision="2" :step="0.01" placeholder="不用加 % 例如 0.05" type="text" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="银联扫码优惠费率" prop="quickPassPay.perferStage.feeRate">-->
          <!--              <el-input-number-->
          <!--                v-model="formData.quickPassPay.perferStage.feeRate"-->
          <!--                :clearable="true"-->
          <!--                :precision="2"-->
          <!--                :step="0.01"-->
          <!--                placeholder="不用加 % 例如 0.05"-->
          <!--                type="text"-->
          <!--              />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="借记卡封顶值" prop="cardPay.debitCap">
              <el-input v-model="formData.cardPay.debitCap" :clearable="true" :min="feeRateList.cardpayDebitCap" style="width: 34%" type="number" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="开通微信支付宝">
          <el-switch v-model="formData.switch" />
        </el-form-item>
        <el-row v-if="formData.switch">
          <el-col :span="12">
            <el-form-item label="微信费率" prop="wxPay.feeRate">
              <el-input-number v-model="formData.wxPay.feeRate" :clearable="true" :precision="2" :step="0.01" placeholder="不用加 % 例如 0.05" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付宝费率" prop="aliPay.feeRate">
              <el-input-number v-model="formData.aliPay.feeRate" :clearable="true" :precision="2" :step="0.01" placeholder="不用加 % 例如 0.05" type="text" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-form-item :rules="[{ required: true, message: '请上传签约协议照片' }]" label="签约协议照片" prop="fileList[5].path">
          <ImageUpload1 v-model="formData.fileList[5].path" />
        </el-form-item> -->
        <template v-if="formData.isUseElecAgreement === false">
          <el-form-item v-if="formData.netType == 2" label="签约协议照片" prop="fileList[5].path">
            <ImageUpload1 v-model="formData.fileList[5].path" />
          </el-form-item>
          <el-form-item v-if="formData.netType != 2" :rules="[{ required: true, message: '请上传签约协议照片' }]" label="签约协议照片" prop="fileList[5].path">
            <ImageUpload1 v-model="formData.fileList[5].path" />
          </el-form-item>
        </template>
      </div>

      <!-- 场景图片 -->
      <div v-if="active >= 3">
        <el-row>
          <el-col :span="12">
            <el-form-item :rules="[{ required: true, message: '请上传门店照片' }]" label="上传门店照片" prop="fileList[6].path">
              <ImageUpload1 v-model="formData.fileList[6].path" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :rules="[{ required: true, message: '请上传收银台照片' }]" label="上传收银台照片" prop="fileList[7].path">
              <ImageUpload1 v-model="formData.fileList[7].path" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item :rules="[{ required: true, message: '请上传店内商品照片' }]" label="上传店内商品照片" prop="fileList[8].path">
          <ImageUpload1 v-model="formData.fileList[8].path" />
        </el-form-item>
      </div>
    </el-form>

    <div class="btn-wrap">
      <el-button v-show="active > 0" style="margin-top: 12px" @click="prev">上一步</el-button>
      <el-button v-show="active < 3" style="margin-top: 12px" @click="next">下一步</el-button>
      <el-button style="margin-top: 12px" @click="submit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import ImageUpload1 from '../ImageUpload.vue';
  import useUserStore from '@/store/modules/user';
  import { reactive, ref } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  import { useDict } from '@/utils/dict';
  import { handleTree } from '@/utils/ruoyi';
  import { areaListByParentId, bankList, businessTypeList, getRegister, openbankListNew, updateRegister } from '@/api/laiqianle/register';
  import { getBank, getBusiness, getCard } from '@/api/system/orc';
  import { getAgent } from '@/api/agent/agent';
  import { isArray } from '@/utils/validate';
  // 字典 laiqianle_register_type 入网类型  laiqianle_card_type 证件类型  laiqianle_license_type 营业执照类型
  const { laiqianle_register_type, laiqianle_card_type, laiqianle_license_type } = useDict('laiqianle_register_type', 'laiqianle_card_type', 'laiqianle_license_type');

  const userStore = useUserStore();
  const router = useRouter();

  const props = defineProps({
    detailId: {
      type: String,
      default: '',
    },
  });

  // 表单 Ref
  const FormRef = ref<FormInstance>();

  // 执照有效期 长期
  const checkboxValue1 = ref(false);
  // 法人证件有效期 长期
  const checkboxValue2 = ref(false);

  // 经营类型
  interface BusinessType {
    id: number;
    name: string;
    code: string;
    pcode: string;
    children: BusinessType[];

    [key: string]: any;
  }

  const businessTypeOptions = ref<BusinessType[]>([]);
  const getBusinessTypeList = async () => {
    const { data } = await businessTypeList();
    businessTypeOptions.value = handleTree(data, 'code', 'pcode', 'children');
  };

  // 商户信息 省市区
  interface provinces {
    id: number;
    name: string;
    code: string;
    pcode: string;

    [key: string]: any;
  }

  let city = ref();
  let province = ref();

  let provinceOptions = ref<provinces[]>([]);
  let cityOptions = ref<provinces[]>([]);
  let cityOptions1 = ref<provinces[]>([]);
  let areaOptions = ref<provinces[]>([]);
  const getProvinceList = async (parentId) => {
    if (parentId === '') return [];
    const { data } = await areaListByParentId(parentId);
    return data;
  };

  const handleProvinceChange = async (value) => {
    cityOptions.value = await getProvinceList(value);
    formData.value['addressinfoId'].city = null;
    formData.value['addressinfoId'].district = null;
  };

  const handleProvinceChange1 = async (value) => {
    cityOptions1.value = await getProvinceList(value);
  };
  const handleCityChange = async (value) => {
    areaOptions.value = await getProvinceList(value);
    formData.value['addressinfoId'].district = null;
  };

  // 银行列表
  interface BankOptions {
    id: string;
    name: string;
    code: string;

    [key: string]: any;
  }

  const bankOptions = ref<BankOptions[]>([]);
  const getBankList = async () => {
    const { rows } = await bankList();
    bankOptions.value = rows;
  };

  // 开户行 根据银行名称查询开户行列表
  interface OpenBankOptions {
    id: string;
    bankName: string;

    [key: string]: any;
  }

  const openBankLoading = ref(false);
  const settleAccountOpenBankOptions = ref<OpenBankOptions[]>([]);
  const filingAccountOpenBankOptions = ref<OpenBankOptions[]>([]);
  const openBankRemoteMethod = async (bankName) => {
    if (!bankName) {
      settleAccountOpenBankOptions.value = [];
      filingAccountOpenBankOptions.value = [];
      return;
    }
    openBankLoading.value = true;
    // const { rows } = await openbankList({ bankName });
    const addressNameObj = cityOptions1.value.find((item) => {
      return item.id === city.value;
    });
    const { data } = await openbankListNew({ bankName, addressName: addressNameObj.name });
    settleAccountOpenBankOptions.value = data;
    filingAccountOpenBankOptions.value = data;
    openBankLoading.value = false;
  };

  let formData = ref({});
  let formRules = reactive<FormRules>({
    netType: [{ required: true, message: '请选择入网类型', trigger: 'change' }],
    isDirectConnect: [{ required: true, message: '请选择是否直接接入', trigger: 'change' }],
    unionPayInsNo: [{ required: true, message: '请输入所属银联机构号', trigger: 'change' }],
    unionPayMrchntNo: [{ required: true, message: '请输入银联商户号', trigger: 'change' }],
    merchantName: [{ required: true, message: '请输入商户名称', trigger: 'change' }],
    shortName: [{ required: true, message: '请输入商户简称', trigger: 'change' }],
    licenceType: [{ required: true, message: '请选择执照类型', trigger: 'change' }],
    licenceNo: [{ required: true, message: '请输入执照编号', trigger: 'change' }],
    licenceExpireDate: [{ required: true, message: '请选择执照有效期', trigger: 'change' }],
    provinces: [{ required: true, message: '请选择省市区', trigger: 'change' }],
    'addressinfoId.province': [{ required: true, message: '请选择省', trigger: 'change' }],
    'addressinfoId.city': [{ required: true, message: '请选择市', trigger: 'change' }],
    'addressinfoId.district': [{ required: true, message: '请选择区', trigger: 'change' }],
    'addressinfoId.address': [{ required: true, message: '请选择账号性质', trigger: 'change' }],
    manageTypeId: [{ required: true, message: '请选择经营类型', trigger: 'change' }],
    manageScope: [{ required: true, message: '请输入经营范围', trigger: 'change' }],
    lepCertName: [{ required: true, message: '请输入法人名称', trigger: 'change' }],
    lepCertType: [{ required: true, message: '请选择证件类型', trigger: 'change' }],
    lepCertNo: [{ required: true, message: '请输入法人证件编号', trigger: 'change' }],
    lepCertExpireDate: [{ required: true, message: '请选择法人证件有效期', trigger: 'change' }],
    contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'change' }],
    contactMobile: [
      { required: true, message: '请输入联系人手机号', trigger: 'change' },
      { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: 'change' },
    ],
    registeredCapital: [{ required: true, message: '请输入注册资金', trigger: 'change' }],
    'settleAccount.bankAccountType': [{ required: true, message: '请选择账号性质', trigger: 'change' }],
    'settleAccount.bankAccountNo': [{ required: true, message: '请输入银行账号', trigger: 'change' }],
    'settleAccount.bankAccountName': [{ required: true, message: '请输入账号名称', trigger: 'change' }],
    'settleAccount.bankCode': [{ required: true, message: '请选择银行类型', trigger: 'change' }],
    'settleAccount.openBank': [{ required: true, message: '请选择开户行', trigger: 'change' }],
    'settleAccount.acctMobile': [
      { required: true, message: '请输入手机号', trigger: 'change' },
      { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: 'change' },
    ],
    'settleAccount.accountIdentityType': [{ required: true, message: '请选择证件类型', trigger: 'change' }],
    'settleAccount.accountIdentityNo': [{ required: true, message: '请输入证件号码', trigger: 'change' }],
    'filingAccount.bankAccountType': [{ required: true, message: '请选择账号性质', trigger: 'change' }],
    'filingAccount.bankAccountNo': [{ required: true, message: '请输入银行账号', trigger: 'change' }],
    'filingAccount.bankAccountName': [{ required: true, message: '请输入账号名称', trigger: 'change' }],
    'filingAccount.bankCode': [{ required: true, message: '请选择银行类型', trigger: 'change' }],
    'filingAccount.openBank': [{ required: true, message: '请选择开户行', trigger: 'change' }],
    'cardPay.debitRate': [
      { required: true, message: '请输入借记卡费率', trigger: 'change' },
      {
        validator: (rule, value, callback) => {
          // 异步验证代码
          if (value < feeRateList.value.cardpayDebitRate) {
            callback(new Error('请输入正确的借记卡费率'));
          } else {
            callback();
          }
        },
        trigger: 'change',
      },
    ],
    'cardPay.feeRate': [
      { required: true, message: '请输入贷记卡费率', trigger: 'change' },
      {
        validator: (rule, value, callback) => {
          // 异步验证代码
          if (value < feeRateList.value.cardpayFeeRate) {
            callback(new Error('请输入正确的贷记卡费率'));
          } else {
            callback();
          }
        },
        trigger: 'change',
      },
    ],
    'cardPay.debitCap': [
      { required: true, message: '请输入借记卡封顶', trigger: 'change' },
      {
        validator: (rule, value, callback) => {
          // 异步验证代码
          if (value < feeRateList.value.cardpayDebitCap) {
            callback(new Error('请输入正确的借记卡封顶'));
          } else {
            callback();
          }
        },
        trigger: 'change',
      },
    ],
    'quickPassPay.perferStage.feeRate': [
      { required: true, message: '请输入银联扫码费率', trigger: 'change' },
      {
        validator: (rule, value, callback) => {
          // 异步验证代码
          if (value < feeRateList.value.preferstageFeerate) {
            callback(new Error('请输入正确的银联扫码费率'));
          } else {
            callback();
          }
        },
        trigger: 'change',
      },
    ],
    'wxPay.feeRate': [
      { required: true, message: '请输入微信费率', trigger: 'change' },
      {
        validator: (rule, value, callback) => {
          // 异步验证代码
          if (value < feeRateList.value.wxpayFeerate) {
            callback(new Error('请输入正确的微信费率'));
          } else {
            callback();
          }
        },
        trigger: 'change',
      },
    ],
    'aliPay.feeRate': [
      { required: true, message: '请输入支付宝费率', trigger: 'change' },
      {
        validator: (rule, value, callback) => {
          // 异步验证代码
          if (value < feeRateList.value.alipayFeerate) {
            callback(new Error('请输入正确的支付宝费率'));
          } else {
            callback();
          }
        },
        trigger: 'change',
      },
    ],
    imgValue1: [{ required: true, message: '请上传证件正面', trigger: 'change' }],
    imgValue2: [{ required: true, message: '请上传证件反面', trigger: 'change' }],
    imgValue3: [{ required: true, message: '请上传营业执照', trigger: 'change' }],
    imgValue4: [{ required: true, message: '请上传结算账户正面', trigger: 'change' }],
    imgValue5: [{ required: true, message: '请上传备案账户正面', trigger: 'change' }],
    imgValue6: [{ required: false, message: '请上传签约协议照片', trigger: 'change' }],
    imgValue7: [{ required: true, message: '请上传门店照片', trigger: 'change' }],
    imgValue8: [{ required: true, message: '请上传收银台照片', trigger: 'change' }],
    imgValue9: [{ required: true, message: '请上传店内商品照片', trigger: 'change' }],
  });

  // 步骤条 上一步 下一步 保存
  const active = ref(0);
  const prev = () => {
    if (active.value === 0) return;
    if (formData.value?.addressinfoId?.address !== null) {
      formData.value?.addressinfoId?.address.replace(/\s*/g, '');
    }
    formData.value.manageScope = formData.value?.manageScope.replace(/[`~!@#$^\-&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】%_+“》《‘·'；：""'。，、？\s]/g, '');

    active.value--;
  };
  const next = () => {
    if (active.value > 3) return;
    if (formData.value?.addressinfoId?.address !== null) {
      formData.value.addressinfoId.address = formData.value?.addressinfoId?.address.replace(/\s*/g, '');
    }
    formData.value.manageScope = formData.value?.manageScope.replace(/[`~!@#$^\-&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】%_+“》《‘·'；：""'。，、？\s]/g, '');

    FormRef.value?.validate((valid) => {
      if (valid) {
        active.value++;
      }
    });
  };
  const submit = () => {
    FormRef.value?.validate((valid) => {
      if (valid) {
        handleFormSubmit();
      }
    });
  };

  const handleFormSubmit = () => {
    let params = JSON.parse(JSON.stringify(formData.value));

    // 条件判断
    // 入网类型为 小微商户  营业执照 执照类型 执照编号 执照有效期 置空
    if (params.netType === 3) {
      params.fileList[2].path = null;
      params.licenceType = null;
      params.licenceNo = null;
      params.licenceExpireDate = null;
    }
    // 是否直接接入 否 置空 所属银联机构号 银联商户号
    if (params.isDirectConnect === false) {
      params.unionPayInsNo = null;
      params.unionPayMrchntNo = null;
    }

    // 账号性质 对私 置空 证件类型 证件号 预留手机号
    if (params.settleAccount.bankAccountType !== 2) {
      params.settleAccount.accountIdentityType = null;
      params.settleAccount.accountIdentityNo = null;
      params.settleAccount.acctMobile = null;
    }

    // 账号性质 对私 并且 入网类型为 企业商户 才显示备案账户 否则置空
    if (
      !(
        (params.netType === '1' && params.settleAccount.bankAccountType === 2) ||
        (params.netType === '2' && params.settleAccount.bankAccountType === 2 && params.settleAccount.bankAccountName !== params.lepCertName)
      )
    ) {
      params.filingAccount = {
        bankAccountType: null, // 账号性质
        bankAccountNo: null, // 银行账号
        bankAccountName: null, // 账号名称
        bankCode: null, // 银行类型
        openBank: null, // 开户行
      };
      params.fileList[9].path = null;
      params.fileList[10].path = null;
      params.fileList[11].path = null;
      params.fileList[12].path = null;
    }

    // 开通微信支付宝 为 否 置空 微信费率 支付宝费率
    if (params.switch === false) {
      params.wxPay.feeRate = null;
      params.aliPay.feeRate = null;
    }

    // 图片
    // 过滤掉 fileList fileUrl为空的
    params.fileList = params.fileList.filter((item) => item.path !== null);

    if (params.settleAccount.bankAccountNo) {
      params.settleAccount.bankAccountNo = params.settleAccount.bankAccountNo.replace(/\s*/g, '');
    }
    if (params.filingAccount.bankAccountNo) {
      params.filingAccount.bankAccountNo = params.filingAccount.bankAccountNo.replace(/\s*/g, '');
    }
    updateRegister(params)
      .then(() => {
        ElMessage.success('修改成功');
        router.push({ path: '/jin/register' });
      })
      .catch((err) => {
        console.log(err);
      });
  };

  // 详情
  const handleDetail = async (id: string) => {
    const { data } = await getRegister(id);
    data.isUseElecAgreement = data.isUseElecAgreement === 'true' || data.isUseElecAgreement === true ? true : false;
    data.netType = data.netType && data.netType.toString();
    data.isDirectConnect = data.isDirectConnect === 'true';
    data.licenceType = data.licenceType && data.licenceType.toString();
    data.manageTypeId = data.manageTypeId && data.manageTypeId.toString();
    data.lepCertType = data.lepCertType && data.lepCertType.toString();
    data.settleAccount.bankCode = data.settleAccount.bankCode && data.settleAccount.bankCode.toString();
    data.settleAccount.bankAccountType = Number(data.settleAccount.bankAccountType);
    data.filingAccount.bankCode = data.filingAccount.bankCode && data.filingAccount.bankCode.toString();
    data.filingAccount.bankAccountType = Number(data.filingAccount.bankAccountType);
    data.settleAccount.accountIdentityType = data.settleAccount.accountIdentityType && data.settleAccount.accountIdentityType.toString();

    // 图片 fileList
    const fileList = [
      { fileTypeId: 11, path: null }, // 证件正面
      { fileTypeId: 12, path: null }, // 证件反面
      { fileTypeId: 15, path: null }, // 营业执照
      { fileTypeId: 13, path: null }, // 结算账户正面
      { fileTypeId: 21, path: null }, // 备案账户正面
      { fileTypeId: 31, path: null }, // 签约协议照片
      { fileTypeId: 18, path: null }, // 门店照片
      { fileTypeId: 19, path: null }, // 收银台照片
      { fileTypeId: 20, path: null }, // 店内商品照片
      { fileTypeId: 41, path: null }, // 委托入款授权照片
      { fileTypeId: 24, path: null }, // 法人和入账人手持身份证合照
      { fileTypeId: 22, path: null }, // 非法人身份证正面
      { fileTypeId: 23, path: null }, // 非法人身份证反面
      { fileTypeId: 34, path: null }, // 商户变更申请表
    ];
    data.fileList = fileList.map((item) => {
      const newItem = data.fileList.find((file) => file.fileTypeId === item.fileTypeId);
      if (newItem) {
        return newItem;
      }
      return item;
    });
    !data.quickPassPay.perferStage && (data.quickPassPay.perferStage = { feeRate: null });
    data['switch'] = data.wxPay.feeRate !== null || data.aliPay.feeRate !== null;
    checkboxValue1.value = data.licenceExpireDate === '2199-12-31';
    checkboxValue2.value = data.lepCertExpireDate === '2199-12-31';
    formData.value = data;
  };
  await getBankList();
  await handleDetail(props.detailId);
  await getBusinessTypeList();
  provinceOptions.value = await getProvinceList(0);
  cityOptions.value = await getProvinceList(formData.value['addressinfoId'].province);
  areaOptions.value = await getProvinceList(formData.value['addressinfoId'].city);

  // 图片上传回调
  const imageUrl = ref('');
  const handleImageEvent = (value: string, type: string) => {
    // value 为空把识别字段置空
    if (!value && type === 'card') {
      formData.value['lepCertNo'] = null;
      formData.value['lepCertName'] = null;
      return;
    }
    if (!value && type === 'business') {
      formData.value['merchantName'] = null;
      formData.value['licenceNo'] = null;
      formData.value['registeredCapital'] = null;
      return;
    }
    if (!value && type === 'bank') {
      formData.value['settleAccount'].bankAccountNo = null;
      return;
    }
    if (!value && type === 'bank1') {
      formData.value['filingAccount'].bankAccountNo = null;
      return;
    }
    imageUrl.value = import.meta.env.VITE_APP_IMG_URL + value;
    // 识别图片
    type === 'card' && CardData();
    type === 'business' && businessData();
    type === 'bank' && backData();
    type === 'bank1' && backData1();
  };
  // 识别身份证
  const CardData = () => {
    getCard({ url: imageUrl.value }).then((res) => {
      formData.value['lepCertNo'] = res.data.face.data.idNumber;
      formData.value['lepCertName'] = res.data.face.data.name;
    });
  };
  // 识别营业执照
  const businessData = () => {
    getBusiness({ url: imageUrl.value }).then((res) => {
      formData.value['merchantName'] = res.data.companyName;
      formData.value['licenceNo'] = res.data.creditCode;
      // formData.value['registeredCapital'] = convertToNumber(res.data.registeredCapital);
    });
  };
  // 识别银行卡
  const backData = () => {
    getBank({ url: imageUrl.value }).then((res) => {
      formData.value['settleAccount'].bankAccountNo = res.data.cardNumber;
    });
  };
  const backData1 = () => {
    getBank({ url: imageUrl.value }).then((res) => {
      formData.value['filingAccount'].bankAccountNo = res.data.cardNumber;
    });
  };

  // 小写金额
  const convertToNumber = (chineseCurrency) => {
    const regex = /[零壹贰叁肆伍陆柒捌玖]/g;
    const mapping = {
      零: 0,
      壹: 1,
      贰: 2,
      叁: 3,
      肆: 4,
      伍: 5,
      陆: 6,
      柒: 7,
      捌: 8,
      玖: 9,
    };
    const matches = chineseCurrency.match(regex);
    const result = matches.reduce((str, char) => {
      return str.replace(char, mapping[char]);
    }, chineseCurrency);
    return result;
  };

  // 费率信息
  const feeRateList: any = ref('');
  const getFeeRate = async () => {
    const res = await getAgent(userStore.userId);
    feeRateList.value = res.data;
  };
  getFeeRate();
</script>

<style lang="scss" scoped>
  .form-wrap {
    width: 70%;
    margin: 30px auto;

    .mb20 {
      margin-bottom: 20px !important;
    }

    .el-form-item {
      width: 95%;
    }

    .el-select {
      width: 100% !important;
    }

    .el-date-editor {
      width: 100% !important;
    }

    :deep(.el-date-editor.el-input) {
      width: 100%;
    }

    :deep(.el-cascader) {
      width: 100% !important;
    }
  }

  .btn-wrap {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>
